/**
 *  NameMangler.java : IceBird project
 *  23:10:50 
 */
package icebird.utils;

import java.util.StringTokenizer;

/**
 * Represents name mangler.
 * @author sergey
 */
public final class NameMangler {
	
	// Dont allow creation.
	private NameMangler() {
	}
	
	/**
	 * Mangle a classname into a ASCII C name
	 * @param s Class name
	 * @return String
	 */
	public static String mangleClassName(String s) {
		if (s == null) {
			throw new IllegalArgumentException();
		}
		 
		s = s.replace('/', '.'); 
		
		StringTokenizer tok = new StringTokenizer(s, ".");
		StringBuilder res = new StringBuilder(32);
		
		res.append('Q');
		res.append(tok.countTokens());
		
		while (tok.hasMoreTokens()) {
			String v = tok.nextToken();
			
			res.append(v.length());
			res.append(v);
		}
		
		return res.toString().intern();
	}
	
	/**
	 * Mangle a classname into a ASCII C name
	 * @return String Mangled class name.
	 */
	public static String mangle(String s) {
		if (s == null) {
			throw new IllegalArgumentException();
		}
		
		char[] src = s.toCharArray();
		int cnt = s.length();
        StringBuilder res = new StringBuilder(cnt);
        
		for (int i = 0; i < cnt; i++) {
			char ch = src[i];
			
			if (((ch >= 'a') && (ch <= 'z'))
				|| ((ch >= 'A') && (ch <= 'Z'))
				|| ((ch >= '0') && (ch <= '9'))) {
				res.append(ch);
			} else {
				res.append(Integer.toHexString(ch));
			}
		}
		
		return res.toString().intern();
	}
}
